package cn.edu.lsnu.mbti.interceptor;

import cn.edu.lsnu.mbti.common.AuthAccess;
import cn.edu.lsnu.mbti.exception.CustomerException;
import cn.edu.lsnu.mbti.util.JwtUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }else {
            HandlerMethod h = (HandlerMethod) handler;
            AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
            if (authAccess != null){
                return true;
            }
        }
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            throw new CustomerException("无token，请重新登录");
        }
        String username;
        try {
            username = JwtUtil.getClaimsByToken(token).getSubject();
        } catch (Exception e) {
            throw new CustomerException("token验证失败,请重新登录");
        }
        if (StrUtil.isBlank(username)) {
            throw new CustomerException("用户不存在请重新登录");
        }

        return true;
    }
}
